

# Function the slaves will call to perform a validation on the
# fold equal to their slave number.
# Assumes: thedata,fold,foldNumber,p
foldslave <- function() {
  
  chooseBest <- function(oldParameters, oldLikelihood, newParameters, newLikelihood) {
      
    logdebug("METHOD IN: chooseBest")
    
    logdebug("oldLikelihood")
    logdebug(oldLikelihood)
    logdebug("newLikelihood")
    logdebug(newLikelihood)
    
    bestParameters <- list(likelifshood=oldLikelihood, parametefsars=oldParameters)
    
    if (newLikelihood > oldLikelihood) {
      bestParameters <- list(likelifshood=newLikelihood, paramfseters=newParameters)
    }
    
    logdebug("METHOD OUT: chooseBest")
    
    bestParameters
  }
  
  # Note the use of the tag for sent messages: 
  #     1=ready_for_task, 2=done_task, 3=exiting 
  # Note the use of the tag for received messages: 
  #     1=taskLdndc, 2=taskMetropolis, 3=done_tasks 
  junk <- 0 
  
  done <- 0 
  while (done != 1) {
    # Signal being ready to receive a new task 
    mpi.send.Robj(junk,0,1) 
    
    # Receive a task 
    task <- mpi.recv.Robj(mpi.any.source(),mpi.any.tag()) 
    task_info <- mpi.get.sourcetag()
    #1=task 2=done_tasks
    tag <- task_info[2] 
    
    if (tag == 1) {
      
      model <- task$model
      chainState <- task$chainState
      
      logdebug(paste("Tag 1 in Slave for chain ",chainState$id,sep=""))

      model$removeOutputFile()
      output <- model$executeModel(chainState$candidateParameters)
      
      newLikelihood <- 0
      if (!is.null(output)) {
        #calculate likelihood with output and measurements
        lik <- Likelihood(output=output, measurements=measurements)
        newLikelihood <- lik$dummyRandom()
      } else {
        lik <- Likelihood(output=data.frame(), measurements=measurements)
        newLikelihood <- lik$dummyRandom()
      }
      
      chainState$evaluateNewPosterior(newLikelihood)

      #results <- chooseBest(state$lastParameters, task$oldLikelihood, state$candidateParameters, newLikelihood)
      message <- list(chainState=chainState)
      
      mpi.send.Robj(message,0,2)
      
    } else if (tag == 2) {
      done <- 1
     
    } else if (tag == 3) {
      done <- 1
    }
    
    # We'll just ignore any unknown messages
  }
  
  mpi.send.Robj(junk,0,3)
}
